package com.syni.mdd.sjb.community.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxAdmin;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxCompany;
import com.syni.mdd.sjb.common.component.mybatis.community.mapper.SjbQywxCompanyMapper;
import com.syni.mdd.sjb.common.component.utils.common.thread.ThreadPoolUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import com.syni.mdd.sjb.community.base.constants.Constants;
import com.syni.mdd.sjb.community.base.entity.bo.CompanyPermanentCodeBo;
import com.syni.mdd.sjb.community.base.quartz.QywxScheduleTask;
import com.syni.mdd.sjb.community.base.service.SjbQywxAdminRoleRelationService;
import com.syni.mdd.sjb.community.base.service.SjbQywxAdminService;
import com.syni.mdd.sjb.community.base.service.SjbQywxCompanyService;
import com.syni.mdd.sjb.community.base.service.SjbQywxCompanyUserService;
import com.syni.mdd.sjb.community.base.utils.OAUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 已安装应用的企业表 服务实现类
 * </p>
 *
 * @author lcc
 * @since 2021-02-23
 */
@Service
@Log4j2
public class SjbQywxCompanyServiceImpl extends ServiceImpl<SjbQywxCompanyMapper, SjbQywxCompany> implements SjbQywxCompanyService {

    @Autowired
    SjbQywxCompanyMapper sjbQywxCompanyMapper;

    @Autowired
    SjbQywxCompanyUserService sjbQywxCompanyUserService;

    @Autowired
    SjbQywxAdminService sjbQxwxAdminService;

    @Autowired
    SjbQywxAdminRoleRelationService sjbQywxAdminRoleRelationService;

    @Autowired
    QywxScheduleTask qywxScheduleTask;

    @Override
    public SjbQywxCompany getByCompanyId(String corpid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SjbQywxCompany.CORP_ID,corpid);
        List<SjbQywxCompany> sjbQywxCompanies = sjbQywxCompanyMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(sjbQywxCompanies)) {
            return sjbQywxCompanies.get(0);
        }
        return null;
    }

    @Override
    public SjbQywxCompany addAuthCode(String authCode) {
        RedisTemplateUtils.getRedisTemplate().opsForHash().put(Constants.REDIS_KEY_AUTH_CODE, authCode, authCode);
        try {
            SjbQywxCompany sjbQywxCompany = handleAuthCode(authCode,authCode);
            RedisTemplateUtils.getRedisTemplate().opsForHash().delete(Constants.REDIS_KEY_AUTH_CODE, authCode);
            return sjbQywxCompany;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * 同步企业微信成员
     */
    @Override
    public void syncEnterpriseMembers(List<SjbQywxCompany> sjbQywxCompanies) {
        if(CollectionUtils.isNotEmpty(sjbQywxCompanies)){
            for(SjbQywxCompany sjbQywxCompany : sjbQywxCompanies) {
                if (StringUtils.isNotBlank(sjbQywxCompany.getCorpId())
                        && StringUtils.isNotBlank(sjbQywxCompany.getPermanentCode())) {
                    sjbQywxCompanyUserService.syncCompanyUserData(sjbQywxCompany.getCorpId(), sjbQywxCompany.getPermanentCode());
                }
            }
        }
    }

    @Override
    @Transactional
    public void cancelAuth(String authCorpId) {
        log.info("cancelAuth:{}",authCorpId);
        //删除公司信息
        SjbQywxCompany sjbQywxCompany = this.getByCompanyId(authCorpId);
        if(sjbQywxCompany != null){
            this.removeById(sjbQywxCompany.getId());
            //删除token
            OAUtils.deleteAccessTokenByPerCode(sjbQywxCompany.getCorpId());
            //删除企业成员
            sjbQywxCompanyUserService.deleteCompanyUserByCorpId(sjbQywxCompany.getCorpId());
        }
        //删除企业管理员
        List<SjbQywxAdmin> sjbQywxAdmins = sjbQxwxAdminService.getByAdminByCorpId(authCorpId);
        if(CollectionUtils.isNotEmpty(sjbQywxAdmins)){
            Set<Integer> adminIds = sjbQywxAdmins.stream().map(SjbQywxAdmin::getId).collect(Collectors.toSet());
            sjbQywxAdminRoleRelationService.deleteAdminRolelations(adminIds);
            sjbQxwxAdminService.removeByIds(adminIds);
        }
    }

    @Override
    public void syncAuthCode() {
        if(RedisTemplateUtils.hasKey(Constants.REDIS_KEY_AUTH_CODE)){
            Map<String,Object> notificationHandler =  RedisTemplateUtils.getRedisTemplate().opsForHash().entries(Constants.REDIS_KEY_AUTH_CODE);
            if(notificationHandler.size() > 0){
                notificationHandler.forEach((key,value) -> {
                    handleAuthCode(key,value.toString());
                    RedisTemplateUtils.getRedisTemplate().opsForHash().delete(Constants.REDIS_KEY_AUTH_CODE, key);
                });
            }
        }
    }

    private SjbQywxCompany handleAuthCode(String suiteID, String authCode) {
        JSONObject jsonObject = OAUtils.getPermanentCode(suiteID,authCode);
        if(jsonObject != null){
            CompanyPermanentCodeBo companyPermanentCodeBo = JSON.parseObject(jsonObject.toJSONString(),CompanyPermanentCodeBo.class);
            SjbQywxCompany sjbQywxCompany = new SjbQywxCompany();
            sjbQywxCompany.setCorpId(companyPermanentCodeBo.getAuth_corp_info().getCorpid());
            sjbQywxCompany.setCorpName(companyPermanentCodeBo.getAuth_corp_info().getCorp_name());
            sjbQywxCompany.setLocation(companyPermanentCodeBo.getAuth_corp_info().getLocation());
            sjbQywxCompany.setCorpUserMax(companyPermanentCodeBo.getAuth_corp_info().getCorp_user_max());
            sjbQywxCompany.setPermanentCode(companyPermanentCodeBo.getPermanentCode());
            sjbQywxCompany.setCorpIndustry(companyPermanentCodeBo.getAuth_corp_info().getCorp_industry());
            if(StringUtils.isNotBlank(companyPermanentCodeBo.getAuth_corp_info().getCorp_full_name())) {
                sjbQywxCompany.setCorpFullName(companyPermanentCodeBo.getAuth_corp_info().getCorp_full_name());
            }
            if(CollectionUtils.isNotEmpty(companyPermanentCodeBo.getAuth_info().getAgent())){
                sjbQywxCompany.setAgentId(companyPermanentCodeBo.getAuth_info().getAgent().get(0).getAgentid().toString());
            }
            saveOrUpdateData(sjbQywxCompany);
            //看看是否同步管理员
            sjbQxwxAdminService.syncAdminInformation(companyPermanentCodeBo);
            List<SjbQywxCompany> sjbQywxCompanies = new ArrayList<>();
            sjbQywxCompanies.add(sjbQywxCompany);
            ThreadPoolUtils.getExecutorService().submit(()->{
                //同步企业成员数据
                sjbQywxCompanyUserService.syncCompanyUserData(sjbQywxCompany.getCorpId(),sjbQywxCompany.getPermanentCode());
                //同步客户数据
                qywxScheduleTask.syncQywxData(sjbQywxCompanies);

            });
            return sjbQywxCompany;
        }
        return null;
    }

    public void saveOrUpdateData(SjbQywxCompany sjbQywxCompany){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SjbQywxCompany.CORP_ID,sjbQywxCompany.getCorpId());
        List<SjbQywxCompany> sjbQywxCompanies = this.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(sjbQywxCompanies)){
            SjbQywxCompany exist = sjbQywxCompanies.get(0);
            sjbQywxCompany.setId(exist.getId());
            BeanUtils.copyProperties(sjbQywxCompany,exist);
            this.updateById(exist);
        }else {
            this.saveOrUpdate(sjbQywxCompany);
        }
    }
}
